// © 2009 Microsoft Corporation.  All rights reserved.
# region Namespaces

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Threading;
using System.Runtime.Serialization;
using System.Web.UI.WebControls;


using RiskDL = Microsoft.InformationSecurity.Risk.RiskDataLayer;
using Microsoft.InformationSecurity.Risk.DataEntity;
using Microsoft.InformationSecurity.Risk.RiskDataContracts;
using Microsoft.InformationSecurity.ISRM.Risk.DataEntity;
using System.Security.Permissions;
using Microsoft.InformationSecurity.CISF.Security;

#endregion

namespace Microsoft.InformationSecurity.Risk.RiskService
{
    #region Public Class ManageRisk
    /// <summary>
    /// This class defines all the implementation for the IManageRisk Interface.
    /// </summary>
    public class ManageRisk : IManageRisk
    {     
        const string eventSource = "Risk Tracker";
        const string logName = "Risk Service";        

        public Collection<ListItem> GetPIIOptions()
        {            
            return RiskDL.ManageRisk.GetPIIOptions();            
        }

        public Collection<ListItem> GetRiskGroups()
        {
            return RiskDL.ManageRisk.GetRiskGroups();
        }

        public Collection<ListItem> GetLocations()
        {
            return RiskDL.ManageRisk.GetLocationOptions();
        }

        public Collection<ListItem> GetOERMClassifications()
        {
            return RiskDL.ManageRisk.GetOERMClassificationOptions();
        }

        public Collection<ListItem> GetDataClassifications()
        {
            return RiskDL.ManageRisk.GetDataClassificationOptions();
        }

        public Collection<NoteData> GetNotes(int riskID)
        {
            return RiskDL.ManageRisk.GetNotes(riskID);
        }

        public Collection<ListItem> GetRiskOrigin()
        {
            return RiskDL.ManageRisk.GetRiskOrigin();
        }

        public Collection<ListItem> GetRiskStatusOptions()
        {
            return RiskDL.ManageRisk.GetRiskStatusOptions();
        }

        public Collection<ListItem> GetRiskImpactOptions()
        {
            return RiskDL.ManageRisk.GetRiskImpactOptions();
        }

        public Collection<ListItem> GetRiskCAOptions()
        {
            return RiskDL.ManageRisk.GetRiskControlAffectivenessOptions();
        }

        public Collection<ListItem> GetRiskFrequencyOptions()
        {
            return RiskDL.ManageRisk.GetRiskFrequencyOptions();
        }

        public int SubmitRisk(RiskData riskInstance, out string submittedbyFullName)
        {            
            try
            {
                PrincipalPermission permission = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, "Risk User", true);
                permission.Demand();

                return RiskDL.ManageRisk.SubmitRisk(riskInstance, out submittedbyFullName);
            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }
        }

        public Collection<History> GetMasterHistoryData(int riskID)
        {
            try
            {
                PrincipalPermission permission = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, "Risk User", true);
                permission.Demand();

                return RiskDL.ManageRisk.GetMasterHistoryData(riskID);
            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }                        
        }

        public Collection<HistoryDetail> GetDetailsHistoryData(int riskID, DateTime createdDate, int personID)
        {
            try
            {
                PrincipalPermission permission = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, "Risk User", true);
                permission.Demand();

                return RiskDL.ManageRisk.GetDetailsHistoryData(riskID, createdDate, personID);
            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }                        
        }

        public Collection<Incident> GetIncidentList(int riskID, string dir, string sort)
        {
            try
            {
                PrincipalPermission permission = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, "Risk User", true);
                permission.Demand();

                return RiskDL.ManageRisk.GetIncidentList(riskID, dir, sort);
            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }
            
        }

        public Incident GetSingleIncidentData(int riskID, int incidentID)
        {
            try
            {
                PrincipalPermission permission = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, "Risk User", true);
                permission.Demand();

                return RiskDL.ManageRisk.GetIncidentData(riskID, incidentID);
            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }
            
        }

        public void InsertIncident(int riskID, string title, string desc, int submittedby)
        {            
            try
            {
                PrincipalPermission permission = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, "Risk User", true);
                permission.Demand();

                RiskDL.ManageRisk.InsertIncident(riskID, desc, title, submittedby);
            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }
        }

        public void UpdatetIncident(int riskID, string title, string desc, int updatedBy, int incidentID)
        {            
            try
            {
                PrincipalPermission permission = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, "Risk User", true);
                permission.Demand();

                RiskDL.ManageRisk.UpdateIncident(riskID, desc, title, updatedBy, incidentID);
            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }
        }

        public DataSet GetCalculatedCRVDataSet(int riskID, int flagforFilter)
        {
            return RiskDL.ManageRisk.GetCalculatedCRVDataSet(riskID, flagforFilter);
        }

        public Collection<OrganizationData> GetRootLevel()
        {
            return RiskDL.ManageRisk.GetRootLevel();
        }

        public Collection<OrganizationData> GetNextLevelOrganizations(int organizationID)
        {
            return RiskDL.ManageRisk.GetNextLevelOrganizations(organizationID);
        }

        public Collection<string> GetTOPNAliases(string alias)
        {
            return RiskDL.ManageRisk.GetTOPNAliases(alias);
        }

        public OrganizationContact GetOrganizationContactXML(string orgaizationlist, string personlist)
        {
            return RiskDL.ManageRisk.GetOrganizationContactXML(orgaizationlist, personlist);
        }

        public object GetPersonID(string alias)
        {
            return RiskDL.ManageRisk.GetPersonID(alias);
        }

        public object GetCRV(int impact, int frequency, int controlAffectiveness)
        {
            return RiskDL.ManageRisk.GetCRV(impact, frequency, controlAffectiveness);
        }

        public object GetPCRV(int crv, Decimal wt)
        {
            return RiskDL.ManageRisk.GetPCRV(crv, wt);
        }

        public object GetRiskRating(int impact, int frequency, int controlAffectiveness)
        {
            return RiskDL.ManageRisk.GetRiskRating(impact, frequency, controlAffectiveness);
        }

        public RiskInformation GetRiskInformation(int riskId)
        {            
            RiskInformation riskInstance = null;
            try
            {
                Microsoft.InformationSecurity.CISF.Security.Principal.CISFPrincipal principal = (CISF.Security.Principal.CISFPrincipal)Thread.CurrentPrincipal;
                Collection<RiskInformation> search = new Collection<RiskInformation>();

                if (principal.IsInRole("Risk User") || principal.IsInRole("Trusted Task User"))
                    riskInstance = RiskDL.ManageRisk.GetRiskInformation(riskId);
                else
                    throw new System.Security.SecurityException("Permission denied.");

            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }
            return riskInstance;
        }
        
        public int UpdateRisk(RiskData riskInstance)
        {
            try
            {
                PrincipalPermission permission = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, "Risk User", true);
                permission.Demand();

                return RiskDL.ManageRisk.UpdateRisk(riskInstance);
            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }            
        }
        
        public Collection<RiskInformation> BasicSearchRisk(string fieldName, string fieldoperator, string sortField, int sortAscDesc, int pageSize, int startIndex, string value1, string value2, int personID, int isRoleFilter)
        {   
            try
            {                
                Microsoft.InformationSecurity.CISF.Security.Principal.CISFPrincipal principal = (CISF.Security.Principal.CISFPrincipal)Thread.CurrentPrincipal;
                Collection<RiskInformation> search = new Collection<RiskInformation>();

                if (principal.IsInRole("Risk User") || principal.IsInRole("Trusted Task User"))
                    search = RiskDL.ManageRisk.BasicSearchRisk(fieldName, fieldoperator, sortField, sortAscDesc, pageSize, startIndex, value1, value2, personID, isRoleFilter);
                else
                    throw new System.Security.SecurityException("Permission denied.");

                return search;
             }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }         
        }
        
        public int BasicSearchRiskCount(string fieldName, string fieldoperator, string value1, string value2, int personID, int isRoleFilter)
        {            
            try
            {                
                Microsoft.InformationSecurity.CISF.Security.Principal.CISFPrincipal principal = (CISF.Security.Principal.CISFPrincipal)Thread.CurrentPrincipal;
                int rows = 0; 

                if (principal.IsInRole("Risk User") || principal.IsInRole("Trusted Task User"))
                    rows = RiskDL.ManageRisk.BasicSearchRiskCount(fieldName, fieldoperator, value1, value2, personID, isRoleFilter);
                else
                    throw new System.Security.SecurityException("Permission denied.");

                return rows;
            }
            catch (System.Security.SecurityException secExcption)
            {
                // Log Error
                if (!EventLog.SourceExists(eventSource))
                    EventLog.CreateEventSource(logName, logName);
                EventLog.WriteEntry(eventSource, secExcption.Message + "\n" + "Stack:" + secExcption.StackTrace, EventLogEntryType.FailureAudit, 1000);

                throw secExcption; // Do not swollow it, let the expeception propagate.
            }            
        }

        public ListItem GetRiskManager(int riskId)
        {
            return RiskDL.ManageRisk.GetRiskManager(riskId);
        }

        public GeneralStats GetGeneralStats()
        {
            return RiskDL.ManageRisk.GetGeneralStats();
        }
    }
    #endregion
}
